package com.atguigu.spzx.user.service.impl;

import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.model.entity.h5.CompleteRegion;
import com.atguigu.spzx.model.entity.h5.UserAddress;
import com.atguigu.spzx.user.mapper.RegionMapper;
import com.atguigu.spzx.user.mapper.UserAddressMapper;
import com.atguigu.spzx.user.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName: UserAddressServiceImpl
 * @Package: com.atguigu.spzx.user.service.impl
 * @Description
 * @Author 孤妤
 * @Date: 2023/12/20 15:53
 */
@Service
@Transactional
public class UserAddressServiceImpl implements UserAddressService {
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    private RegionMapper regionMapper;

    @Override
    @Transactional(readOnly = true)
    public List<UserAddress> findUserAddressList() {
        Long userId = AuthContextUtil.getUserInfo().getId();
        return userAddressMapper.findUserAddressList(userId);
    }

    @Override
    @Transactional(readOnly = true)
    public UserAddress findUserAddressById(Long id) {
        return userAddressMapper.selectUserAddressById(id);
    }

    @Override
    public void changeUserAddress(UserAddress userAddress) {
        // 判断是不是默认地址
        if (userAddress.getIsDefault() == 1) userAddressMapper.updateAllUserAddressIsDefault();
        userAddressMapper.updateUserAddress(userAddress);
    }

    @Override
    public void addUserAddress(UserAddress userAddress) {
        // 查询全部地址
        CompleteRegion completeRegion = regionMapper.findRegion(userAddress.getDistrictCode());
        // 进行拼接
        String regionStr = completeRegion.getProvince() + completeRegion.getCity() + completeRegion.getDistrict()+userAddress.getAddress();
        Long userId = getUserId();
        userAddress.setUserId(userId);
        userAddress.setFullAddress(regionStr);
        // 判断是不是默认地址
        if (userAddress.getIsDefault() == 1) userAddressMapper.updateAllUserAddressIsDefault();
        userAddressMapper.insertUserAddress(userAddress);
    }

    @Override
    public void removeUserAddressById(Long id) {
        userAddressMapper.deleteUserAddressById(id);
    }

    private Long getUserId() {
        // 获取用户id
        return AuthContextUtil.getUserInfo().getId();
    }
}
